<template>
    <div>
        <el-upload :headers="headers" :action="uploadAction" class="avatar-uploader" :before-upload="beforeUpload"
            :on-remove="handleRemove" :on-success="handleUploadSuccess" :auto-upload="true" :show-file-list="false">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <el-icon v-else class="avatar-uploader-icon">
                <Plus />
            </el-icon>
        </el-upload>
    </div>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue';
import { defineEmits } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus';

const emInput = defineEmits(["changeUrl"])

const headers = computed(() => { return { token: sessionStorage.getItem("token") } });
const uploadAction = "/api" + '/system-api/admin-api/upload/image';
const dialogVisible = ref(false);
const imageUrl = ref("")

const emitInput = (val: any) => {
    emInput("changeUrl", val)
}
const handleRemove = (file: any, fileList: any) => {
    //   del(file.url)
    emitInput(fileList);
}
const beforeUpload = (file: any) => {
    let spt = file.name.split(".")
    let type = spt[spt.length - 1]
    if (type !== 'jpg' && type !== 'png') {
        ElMessage.error('图片格式不正确!')
        return false
    } else if (file.size / 1024 / 1024 > 2) {
        ElMessage.error('图片大小不能超过 2MB!')
        return false
    }
    return true
}
const handleUploadSuccess = (res: any, file: any) => {
    let url = res.data
    imageUrl.value = url
    emitInput(url)
}

</script>

<style scoped>
/* .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
} */
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 148px;
    height: 148px;
    line-height: 146px;
    text-align: center;
}

.avatar {
    width: 148px;
    height: 148px;
    display: block;
}
</style>